package com.mhr.controller;

import com.mhr.pojo.Admin;
import com.mhr.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author manster
 * @Date 2021/4/21
 **/
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @GetMapping(value = "login")
    public String toLogin(){
        return "login";
    }

    @PostMapping(value = "login")
    public String login(@RequestParam(name = "username")String name,
                        @RequestParam(name = "password")String password,
                        HttpServletRequest request,
                        Model model){

        Admin admin = loginService.login(name);
        //管理员是否存在
        if(!StringUtils.isEmpty(admin)){
            //判断密码是否正确
            if(DigestUtils.md5DigestAsHex(password.getBytes()).equals(admin.getPassword())){
                request.getSession().setAttribute("admin",admin);
                return "redirect:/list";
            }
            model.addAttribute("msg","密码错误");
            return "login";

        }

        model.addAttribute("msg","用户不存在");
        return "login";

    }

}
